package com.example.mongodb.mongodb.controller.rabbitmq.mqttl;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class RabbitmqTTL {

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("123.207.179.78");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("admin");
        factory.setPassword("admin");

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            //使用direct模式
            Map<String,Object> map = new HashMap<String,Object>();
            //消息中消息队列过期时间
            map.put("x-message-ttl",10*1000);
            //如果消息队列没有消费者，则10秒消息过期，消息队列也删除
            map.put("x-expires",60*1000);
            channel.queueDeclare("queue.ttl.waiting",true,false,false,map);

            //申明exchange 交换机
            channel.exchangeDeclare("ex.ttl.waiting", BuiltinExchangeType.DIRECT,true,false,null);

            //绑定队列以及交换机和routingkey
            channel.queueBind("queue.ttl.waiting","ex.ttl.waiting","key.ttl.waiting");


            // 下面参数 2 代表持久化消息
            AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder().contentEncoding("utf-8").deliveryMode(2).build();
            //发送消息
            channel.basicPublish("ex.ttl.waiting","key.ttl.waiting",basicProperties,"等待的订单号".getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }
}
